import React, { useState, useEffect } from 'react'
import { Button, Input, Icon } from 'antd';

import styles from './index.less'


export default function ({ tableColumns }) {
	const [isExpand, setisExpand] = useState(false);//是否展开
	const [filterAllQueryHead, setFilterAllQueryHead] = useState([]);//筛选出参与查询的字段
	const [queryComponentsArr, setqueryComponentsArr] = useState([]);//查询字段头
	const [queryParams, setqueryParams] = useState({});

	const [mystyle, setmystyle] = useState({ expandIcon: 'rotate(0turn)' });

	useEffect(() => {
		setqueryComponentsArr(filterNeedHead(tableColumns));
		setqueryParams(initQueryParams(tableColumns));
	}, [])

	useEffect(() => {
		//是否展开
		if (isExpand) {
			setmystyle({ ...mystyle, expandIcon: 'rotate(0.5turn)' })
			setqueryComponentsArr(filterNeedHead(tableColumns, filterAllQueryHead.length));
		} else {
			setmystyle({ ...mystyle, expandIcon: 'rotate(0)' })
			setqueryComponentsArr(filterNeedHead(tableColumns));
		}
	}, [isExpand])

	//筛选出所展示的查询字段
	const filterNeedHead = (data, num = 2) => {
		let filterArr = data.filter((item, index) => item.showQueryHead);
		setFilterAllQueryHead(filterArr);
		return filterArr.slice(0, num);
	}

	const initQueryParams = (data) => {
		let obj = {};
		let filterArr = data.filter((item, index) => item.showQueryHead);
		for (const item of filterArr) {
			obj[item.dataIndex] = item.defaultItemData || ''
		}
		return obj;
	}


	const changeItemParam = (val, dataIndex) => {
		console.log(val, dataIndex)
		setqueryParams({
			...queryParams,
			[dataIndex]: val
		})
	}


	const queryHandle = () => {
		console.log(queryParams)
	}

	return (
		<div className={styles.container}>
			{
				queryComponentsArr.map((item, index) => (
					<div key={item.dataIndex} className={styles.item}>
						<span className={styles.itemLabel}>{item.title}：</span>
						{
							item.renderDiyComponents ?
								item.renderDiyComponents(item.dataIndex, changeItemParam) :
								<Input
									type='text'
									value={queryParams[item.dataIndex]}
									onChange={(e) => {
										changeItemParam(e.target.value, item.dataIndex)
									}}
								></Input>
						}
					</div>
				))
			}
			<div className={styles.item} style={{ justifyContent: 'flex-end' }}>
				<Button style={{ marginRight: '8px' }}>重置</Button>
				<Button style={{ marginRight: '8px' }} type="primary" onClick={queryHandle}>查询</Button>
				<div className={styles.textBtn} onClick={() => { setisExpand(!isExpand) }}>
					<span>{isExpand ? '收起' : '展开'}</span>
					<Icon className={styles.textBtnIcon} style={{ transform: mystyle.expandIcon }} type="down" />
				</div>
			</div>
		</div>
	)
}
